<template>
  <div>
    <org-tree
      :data="treeData"
      :props="defaultProps"
      :label-class-name="labelClass"
      :render-content="renderContent"
    />
    <div>
      <el-button type="primary" @click="saveTree">生成策略树</el-button>
      <el-button @click="resetTree">重置</el-button>
    </div>
  </div>
</template>

<script>
import OrgTree from "vue2-org-tree";
import "vue2-org-tree/dist/style.css";
import {
  getPropertyKeys,
  getPropertyValues,
} from "@/api/access_property/property";
export default {
  components: { OrgTree },
  data() {
    return {
      treeData: {
        id: 1,
        label: "AND",
        type: "logic",
        children: [
          {
            id: 2,
            type: "condition",
            condition: {
              key: "",
              value: "",
            },
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      keyOptions: [],
      valueOptions: {},
    };
  },
  created() {
    this.loadKeys();
    this.expression = "";
    this.showExpression = false;
  },
  methods: {
    async loadKeys() {
      this.loadingKeys = true;
      this.keyError = null;
      try {
        const response = await getPropertyKeys();
        // 假设API返回的是字符串数组
        this.keyOptions = response.data.map((item) => ({
          label: item,
          value: item,
        }));
      } catch (error) {
        console.error("加载K值失败:", error);
        this.$message.error("加载K值失败，请检查网络连接");
      }
    },

    // 从API加载V值
    async loadValues(key) {
      this.loadingValues = true;
      try {
        const response = await getPropertyValues(key);
        // 假设API返回的是字符串数组
        this.$set(
          this.valueOptions,
          key,
          response.data.map((item) => ({
            label: item,
            value: item,
          }))
        );
      } catch (error) {
        console.error("加载V值失败:", error);
        this.$message.error("加载V值失败，请检查网络连接");
      }
    },

    // 给逻辑节点和条件节点加不同的样式
    labelClass(data) {
      return data.type === "logic" ? "logic-node" : "condition-node";
    },

    // 渲染每个节点的内容（自定义）
    renderContent(h, data) {
      if (data.type === "condition") {
        return (
          <div class="node-box">
            <el-select
              size="mini"
              value={data.condition.key}
              style="width: 100px"
              onInput={(v) => this.updateConditionKey(data, v)}
              placeholder="请选择K值"
            >
              {this.keyOptions.map((option) => (
                <el-option
                  label={option.label}
                  value={option.value}
                ></el-option>
              ))}
            </el-select>

            <el-select
              size="mini"
              value={data.condition.value}
              style="width: 120px"
              onInput={(v) => this.updateConditionValue(data, v)}
              placeholder="请选择V值"
              filterable
              allow-create
            >
              {this.valueOptions[data.condition.key] &&
                this.valueOptions[data.condition.key].map((option) => (
                  <el-option
                    label={option.label}
                    value={option.value}
                  ></el-option>
                ))}
            </el-select>

            <el-button
              type="text"
              size="mini"
              onClick={() => this.addCondition(data)}
            >
              +
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.removeNode(data)}
            >
              -
            </el-button>
          </div>
        );
      } else {
        return (
          <div class="node-box">
            <el-select
              size="mini"
              value={data.label}
              style="width: 80px"
              onInput={(v) => (data.label = v)}
            >
              <el-option label="AND" value="AND"></el-option>
              <el-option label="OR" value="OR"></el-option>
            </el-select>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.addCondition(data)}
            >
              +条件
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.addGroup(data)}
            >
              +组
            </el-button>
            <el-button
              type="text"
              size="mini"
              onClick={() => this.removeNode(data)}
            >
              -
            </el-button>
          </div>
        );
      }
    },

    // 更新条件节点的K值
    async updateConditionKey(node, key) {
      node.condition.key = key;
      // 重置值为空，因为K值改变了，V值也应该重新选择
      node.condition.value = "";

      // 如果这个K值的V值选项尚未加载，则从API加载
      if (key && !this.valueOptions[key]) {
        await this.loadValues(key);
      }
    },

    // 更新条件节点的V值
    updateConditionValue(node, value) {
      node.condition.value = value;
    },

    // 添加条件节点
    addCondition(parent) {
      if (!parent.children) this.$set(parent, "children", []);
      parent.children.push({
        id: Date.now(),
        type: "condition",
        condition: {
          key: "",
          value: "",
        },
      });
    },

    // 添加逻辑分组
    addGroup(parent) {
      if (!parent.children) this.$set(parent, "children", []);
      parent.children.push({
        id: Date.now(),
        type: "logic",
        label: "AND",
        children: [],
      });
    },

    // 删除节点
    removeNode(node) {
      // 根节点不能删
      if (node.id === this.treeData.id) {
        this.$message.error("根节点不能删除");
        return;
      }

      const findAndRemove = (target, parent) => {
        if (!parent.children) return;
        parent.children = parent.children.filter((c) => c.id !== target.id);
        parent.children.forEach((c) => findAndRemove(target, c));
      };
      findAndRemove(node, this.treeData);
    },

    // 生成策略表达式
    generateExpression(data) {
      if (data.type === "condition") {
        return data.condition.key && data.condition.value
          ? `${data.condition.key}:${data.condition.value}`
          : "";
      } else {
        const childrenExpressions = data.children
          .map((child) => this.generateExpression(child))
          .filter((exp) => exp); // 过滤掉空表达式

        if (childrenExpressions.length === 0) return "";
        if (childrenExpressions.length === 1) return childrenExpressions[0];

        // 修复OR逻辑显示问题
        const operator = data.label.toLowerCase();
        return `(${childrenExpressions.join(` ${operator} `)})`;
      }
    },

    // 更新表达式
    updateExpression() {
      this.expression = this.generateExpression(this.treeData);
    },

    // 保存策略树
    saveTree() {
      this.updateExpression();
      this.showExpression = true;
      console.log("策略表达式：", this.expression);
      console.log("策略树结构：", JSON.stringify(this.treeData, null, 2));
      this.$message.success(`策略已保存: ${this.expression}`);
    },

    // 重置策略树
    resetTree() {
      this.treeData = {
        id: 1,
        label: "AND",
        type: "logic",
        children: [
          {
            id: 2,
            type: "condition",
            condition: {
              key: "",
              value: "",
            },
          },
        ],
      };
      this.expression = "";
      this.showExpression = false;
      this.$message.info("策略树已重置");
    },
  },
};
</script>

<style>
.logic-node {
  background: #409eff;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}
.condition-node {
  background: #67c23a;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
}
.node-box {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>